package com.tjb.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tjb.reggie.common.R;
import com.tjb.reggie.common.TjbException;
import com.tjb.reggie.entity.User;
import com.tjb.reggie.service.UserService;
import com.tjb.reggie.util.MailUtil;
import com.tjb.reggie.util.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author tjb
 * @version 1.0
 * @date 2022/8/26 10:50
 */
@Api(tags = "用户相关的接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private MailUtil mailUtil;
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 移动端获取验证码
     * @param user
     * @param session
     * @return
     */
    @ApiOperation(value = "发送短信")
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        System.out.println("进入发送controller");
        //获取手机号
        String phone = user.getPhone();
        System.out.println(phone);
        if (!StringUtils.isEmpty(phone)){
            //生成随机的四位验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4).toString();
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖", "", phone, code);
            mailUtil.sendSimpleMail(phone, "你的手机验证码为："+code+",两分钟有效，请妥善保管。");
            System.out.println("发送成功");
            //将生成的验证码保存到Session
//            session.setAttribute(phone, code);
            //缓存到redis
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功");
        }
        return R.error("手机验证码发送失败");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new TjbException("手机号或验证码不能为空");
        }
        //从session中获取保存的验证码
        //String sessionCode = session.getAttribute(phone).toString();
        String sessionCode = redisTemplate.opsForValue().get(phone).toString();
        //进行验证码对比,（页面提交的验证码和session中保存的验证码对比）
        if (sessionCode != null && sessionCode.equals(code)){
            //如果能够对比成功，说明登录成功
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            //登录成功，删除缓存
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误");
    }
    @PostMapping("loginout")
    public R<String> loginout(HttpServletRequest request){
        //清除session中的值
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    /**
     * 获取用户
     * @param user
     * @return
     */
    @GetMapping("getUser")
    public R<User> getUser(User user){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (user.getId() != null){
            wrapper.eq(User::getId, user.getId());
        }
        if (user.getPhone() != null){
            wrapper.eq(User::getPhone, user.getPhone());
        }
        User one = userService.getOne(wrapper);
        return R.success(one);
    }
    /**
     * 更新用户信息
     */
    @PutMapping("updateUser")
    public R<String> updateUser(User user){
        userService.updateById(user);
        return R.success("更新成功");
    }
}
